package cc.rengu.igas.share.core.service.channel.momp;

import cc.rengu.igas.momp.facade.base.Header;
import cc.rengu.igas.momp.facade.bean.CouponBriefInfoBean;
import cc.rengu.igas.momp.facade.request.ReturnCouponRequest;
import cc.rengu.igas.momp.facade.response.ReturnCouponResponse;
import cc.rengu.igas.momp.facade.result.Result;
import cc.rengu.igas.share.common.constant.ShareParamConstant;
import cc.rengu.igas.share.common.constant.ShareServiceConstant;
import cc.rengu.igas.share.common.constant.TransCacheConstant;
import cc.rengu.igas.share.core.model.CouponInfo;
import cc.rengu.oltp.service.base.ChannelBaseService;
import cc.rengu.oltp.service.common.constant.AppParamConstant;
import cc.rengu.oltp.service.common.constant.TreeNodeConstant;
import cc.rengu.oltp.service.common.entity.ChannelCallCfg;
import cc.rengu.oltp.service.common.entity.MchntOrderInfo;
import cc.rengu.oltp.service.common.entity.PayOrderInfo;
import cc.rengu.oltp.service.common.entity.UserOrderInfo;
import cc.rengu.oltp.service.common.enums.*;
import cc.rengu.oltp.service.model.BizException;
import cc.rengu.oltp.service.model.BizResponse;
import cc.rengu.oltp.service.model.OrderInfo;
import cc.rengu.oltp.service.model.TxnInfo;
import cc.rengu.oltp.service.realize.DubboService;
import cc.rengu.oltp.service.realize.impl.DubboServiceImpl;
import cc.rengu.oltp.utility.util.*;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Optional;

/**
 * 卡卷退回服务
 * Created by wangcheng on 2021/7/16 16:10
 */
public class ReturnCouponService extends ChannelBaseService {
    @Override
    public Object callPreProc(TxnInfo txnInfo, ChannelCallCfg channelCallCfg, OrderInfo orderInfo) throws Exception {
        XmlTreeUtil xmlTreeUtil = new XmlTreeUtil();
        Header mompHeader = new Header();
        mompHeader.setInstId(xmlTreeUtil.getXmlTreeStringValue(TreeNodeConstant.INST_ID));
        mompHeader.setChanlId(channelCallCfg.getMsgSrcId());
        mompHeader.setSrcSysId(AppParamConstant.SYS_ID);
        mompHeader.setBizType(AppParamConstant.DEFAULT_BIZ_TYPE);
        mompHeader.setVersion(ShareParamConstant.DUBBO_VSERSION);
        mompHeader.setTxnNum(channelCallCfg.getCallChannelTxn());
        mompHeader.setTraceNo(xmlTreeUtil.getXmlTreeStringValue(TreeNodeConstant.SYS_SEQ_NUM) + channelCallCfg.getCallIndex());
        mompHeader.setTransTime(xmlTreeUtil.getXmlTreeStringValue(TreeNodeConstant.TRANS_TIME));
        mompHeader.setTransDate(xmlTreeUtil.getXmlTreeStringValue(TreeNodeConstant.TRANS_DATE));
        ReturnCouponRequest returnCouponRequest = new ReturnCouponRequest();
        returnCouponRequest.setHeader(mompHeader);
        List<String> couponIdList = (List<String>) GlobalTransUtil.getCacheValue(TransCacheConstant.COUPON_ID_LIST);
        if (null == couponIdList) {
            rglog.error("交易未上送卡卷列表信息!");
            return null;
        }
        List<CouponBriefInfoBean> couponBriefInfoBeanList = new ArrayList<>();
        //卡卷锁定状态：0-锁定，1-退回(退回给用户)，2-解锁(不退回用户)
        String couponLockFlag = (String) GlobalTransUtil.getCacheValue(TransCacheConstant.COUPON_LOCK_FLAG);
        for (String couponId : couponIdList) {
            CouponBriefInfoBean couponBriefInfoBean = new CouponBriefInfoBean();
            couponBriefInfoBean.setCouponNo(couponId);
            couponBriefInfoBean.setCouponLockFlag(couponLockFlag);
            couponBriefInfoBeanList.add(couponBriefInfoBean);
        }
        returnCouponRequest.setCouponInfoList(couponBriefInfoBeanList);
        return returnCouponRequest;
    }

    @Override
    public PayOrderInfo generatePayOrderInfo(ChannelCallCfg channelCallCfg, OrderInfo orderInfo, Object request) throws Exception {
        XmlTreeUtil xmlTreeUtil = new XmlTreeUtil();
        String sysSeqNum = xmlTreeUtil.getXmlTreeStringValue(TreeNodeConstant.SYS_SEQ_NUM);
        UserOrderInfo userOrderInfo = orderInfo.getUserOrderInfo();
        PayOrderInfo payOrderInfo = new PayOrderInfo();
        BeanUtil.beanCopy(userOrderInfo, payOrderInfo);
        payOrderInfo.setTxnNum(userOrderInfo.getTxnNum());
        payOrderInfo.setSysSeqNum(sysSeqNum);
        payOrderInfo.setOrderCcy(userOrderInfo.getOrderCcy());
        payOrderInfo.setMsgDstId(channelCallCfg.getCallChannelId());
        payOrderInfo.setDstCallIndex(channelCallCfg.getCallIndex());
        payOrderInfo.setChannelSeqNum(sysSeqNum + channelCallCfg.getCallIndex());
        payOrderInfo.setChannelReconKey(sysSeqNum + channelCallCfg.getCallIndex());
        payOrderInfo.setDstTxnNum(channelCallCfg.getCallChannelTxn());
        payOrderInfo.setPayType(PayTypeEnum.COUPON.getPayType());
        payOrderInfo.setPayerAcctType(AcctTypeEnum.ALL.getAcctType());
        payOrderInfo.setBizStatus(BizStatusEnum.PROCESSING.getStatus());
        payOrderInfo.setTransStatus(TransStatusEnum.TRANS_INIT.getStatus());
        StringBuilder payerInfo = new StringBuilder();
        List<String> couponIdList = (List<String>) GlobalTransUtil.getCacheValue(TransCacheConstant.COUPON_ID_LIST);
        if (null != couponIdList) {
            for (String couponId : couponIdList) {
                payerInfo = new StringBuilder(couponId + payerInfo + ",");
            }
            payOrderInfo.setPayerRemark(payerInfo.toString());
        }
        payOrderInfo.setCreateTime(DateUtil.getCurrentDateTime("yyyy-MM-dd HH:mm:ss.SSS"));
        return payOrderInfo;
    }

    @Override
    public Object callProc(ChannelCallCfg channelCallCfg, Object request) throws Exception {
        ReturnCouponRequest returnCouponRequest = (ReturnCouponRequest) request;
        /* Step1：调用接口，获取结果 */
        Result<ReturnCouponResponse> callResult;
        DubboService dubboService = new DubboServiceImpl();
        if (AppParamConstant.YES.equals(channelCallCfg.getSyncCallFlag())) {
            /* Step1.1：异步调用 */
            int iReturnCode;
            int callTimes = 0 == channelCallCfg.getSyncQueryRepeatNum() ? 1 : channelCallCfg.getSyncQueryRepeatNum();
            int gatTime = channelCallCfg.getSyncQueryRepeatTime();
            int gatType = StringUtil.isEmptyOrNull(channelCallCfg.getSyncQueryGapType()) ? 0 : Integer.parseInt(channelCallCfg.getSyncQueryGapType());
            if (ChannelCallModeEnum.LOCAL.getMode().equals(channelCallCfg.getChannelCallMode())) {
                /* Step1.1.1：异步应用内调用 */
                Class clasz = Class.forName(ShareServiceConstant.MOMP_COUPON_MANAGEMENT_SERVICE_INNER_PATH);
                iReturnCode = dubboService.asynCallDubboInnerMethod(clasz, ShareServiceConstant.MOMP_RETURN_COUPON_METHOD, returnCouponRequest, channelCallCfg.getSyncResultServiceName(), callTimes, gatType, gatTime);
            } else if (ChannelCallModeEnum.REMOTE.getMode().equals(channelCallCfg.getChannelCallMode())) {
                /* Step1.1.2：异步远程调用 */
                iReturnCode = dubboService.asynCallDubboService(ShareServiceConstant.MOMP_COUPON_MANAGEMENT_SERVICE, ShareServiceConstant.MOMP_RETURN_COUPON_METHOD, returnCouponRequest, channelCallCfg.getSyncResultServiceName(), callTimes, gatType, gatTime);
            } else {
                rglog.error("不支持的通道服务调用方式:{}，交易拒绝!", channelCallCfg.getChannelCallMode());
                throw new BizException(OltpRpcdEnum.CALL_BIZ_SERVICE_ERROR);
            }
            if (0 == iReturnCode) {
                return new BizResponse<>(OltpRpcdEnum.TRANS_SUCCESS.getRespCode(), OltpRpcdEnum.TRANS_SUCCESS.getRespDesc());
            } else {
                return new BizResponse<>(OltpRpcdEnum.CALL_BIZ_SERVICE_ERROR.getRespCode(), OltpRpcdEnum.CALL_BIZ_SERVICE_ERROR.getRespDesc());
            }
        } else {
            /* Step1.2：同步调用 */
            if (ChannelCallModeEnum.LOCAL.getMode().equals(channelCallCfg.getChannelCallMode())) {
                /* Step1.2.1：同步应用内调用 */
                Class clasz = Class.forName(ShareServiceConstant.MOMP_COUPON_MANAGEMENT_SERVICE_INNER_PATH);
                callResult = (Result<ReturnCouponResponse>) dubboService.callDubboInnerMethod(clasz, ShareServiceConstant.MOMP_RETURN_COUPON_METHOD, returnCouponRequest);
            } else if (ChannelCallModeEnum.REMOTE.getMode().equals(channelCallCfg.getChannelCallMode())) {
                /* Step1.2.2：同步远程调用 */
                callResult = (Result<ReturnCouponResponse>) dubboService.callDubboService(ShareServiceConstant.MOMP_COUPON_MANAGEMENT_SERVICE, ShareServiceConstant.MOMP_RETURN_COUPON_METHOD, returnCouponRequest);
            } else {
                rglog.error("不支持的通道服务调用方式:{}，交易拒绝!", channelCallCfg.getChannelCallMode());
                throw new BizException(OltpRpcdEnum.CALL_BIZ_SERVICE_ERROR);
            }
        }
        return callResult;
    }

    @Override
    public Object querySyncCallResult(PayOrderInfo payOrderInfo, Object request) {
        return null;
    }

    @Override
    public OrderInfo callResultOrderProc(OrderInfo orderInfo, String payOrderIndex, TransStatusEnum transStatusEnum, Object response) throws Exception {
        OrderInfo updateOrderInfo = new OrderInfo();
        Result<ReturnCouponResponse> callResult = (Result<ReturnCouponResponse>) response;
        Optional<PayOrderInfo> payOrderInfoOpt = orderInfo.getPayOrderInfoList().stream().filter(item -> item.getDstCallIndex().equals(payOrderIndex)).findFirst();
        if (payOrderInfoOpt.isPresent() && null != callResult && null != callResult.getResult()) {
            PayOrderInfo payOrderInfo = payOrderInfoOpt.get();
            payOrderInfo.setTransStatus(transStatusEnum.getStatus());
            ReturnCouponResponse returnCouponResponse = callResult.getResult();
            payOrderInfo.setRespCode(returnCouponResponse.getRespCode());
            payOrderInfo.setRespDesc(returnCouponResponse.getRespDesc());
            payOrderInfo.setUpdateTime(DateUtil.getCurrentDateTime("yyyy-MM-dd HH:mm:ss.SSS"));
            switch (transStatusEnum) {
                case TRANS_SUCC:
                    payOrderInfo.setBizStatus(BizStatusEnum.FINISH.getStatus());
                    break;
                case TRANS_TIMEOUT:
                    payOrderInfo.setBizStatus(BizStatusEnum.PROCESSING.getStatus());
                    break;
                case SYSTEM_REJECT:
                    payOrderInfo.setBizStatus(BizStatusEnum.FAILED.getStatus());
                    break;
                default:
                    break;
            }
            updateOrderInfo.setPayOrderInfoList(Collections.singletonList(payOrderInfo));
            return updateOrderInfo;
        }
        return null;
    }
}
